package com.kaizzi.data.jdl.service;

import com.kaizzi.data.ppt.CreateJdlPPT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author Kzen
 * @Description description
 * @date 2020/10/16
 */
@Service
@Slf4j
public class DownloadService {

    @Resource
    private CreateJdlPPT createJdlPPT;

    public void download(HttpServletRequest request, HttpServletResponse response) {
        try {
            //验证ppt是否生成成功 ，失败 ，返回异常数据名称

            //这里是下载以后的文件叫做什么名字。我这里是以时间来定义名字的。
            String pptName = "downLoad.pptx";
            downCfg(pptName, request, response);
            OutputStream out;
            FileInputStream inputStream = new FileInputStream("jdl.pptx");
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void downCfg(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 判断浏览器，进行不同的加密，这样下载的时候保存的文件名就不会乱码
        String userAgent = request.getHeader("User-Agent");
        // 针对IE或者以IE为内核的浏览器：
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
    }
}
